use std::fs::{File, OpenOptions};
use std::io::Write;
use cgroups_rs::{Cgroup, CgroupPid, Controller};
use cgroups_rs::cgroup_builder::CgroupBuilder;
use cgroups_rs::memory::MemController;
use libc::pid_t;
pub fn cgroup_limit_mem(pid: pid_t) -> Result<(), String> {
    let hier = cgroups_rs::hierarchies::auto();
    let root_path = hier.root();
    let cg: Cgroup = CgroupBuilder::new("my-docker")
        .memory()
        .kernel_memory_limit(1024 * 1024) //1Mb
        .memory_hard_limit(1024 * 1024) //1Mb
        .done()
        .build(hier).unwrap();
    let filename = "cgroup.procs".to_string();
    let path_buf = root_path.join("my-docker").join(&filename);

    OpenOptions::new().write(true).open(path_buf)
        .and_then(|mut f| {
            f.write_all(format!("{}", pid).as_bytes())
        }).map_err(|e| e.to_string())?;
    Ok(())
}

pub fn cgroup_limit_mem_rm() -> Result<(), String> {
    let hier = cgroups_rs::hierarchies::auto();
    let cgroup = Cgroup::load(hier, "my-docker");
    Ok(cgroup.delete().map_err(|e|e.to_string())?)
}